using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Common;
using System.Globalization;
using System.Collections;
using System.Text;
using System.Data;
using System.Web.Configuration;
using ResourceBlender.DAL;
using ResourceBlender.Core;

public partial class Templates : LocalPage
{
    /// <summary>
    /// Disables gridlines if there are no templates
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void Page_Load(object sender, EventArgs e)
    {
        pnlAddError.Visible = false;
        if(!Page.IsPostBack) {
            mltMain.ActiveViewIndex = 0;
            BindItemsGrid();
        }
    }


    /// <summary>
    /// Binds the main GridView and removes gridlines if necessary.
    /// </summary>
    private void BindItemsGrid() {
        grdTemplates.DataBind();
        if(grdTemplates.Rows.Count == 0) {
            grdTemplates.GridLines = GridLines.None;
        } else {
            grdTemplates.GridLines = GridLines.Both;
        }
    }


    /// <summary>
    /// Process edit/delete commands from the GridView
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewCommandEventArgs"/> instance containing the event data.</param>
    protected void grdTemplates_RowCommand(object sender, GridViewCommandEventArgs e) {
        try {
            string templateId = e.CommandArgument.ToString();
            RBTemplate template = ResourceBlenderDAL.GetTemplate(templateId);
            switch(e.CommandName) {
                case "doedit":
                    txtTemplateName.Text = template.Name;
                    txtFileName.Text = template.FileName;
                    txtFileStart.Text = template.FileStart;
                    txtFileEnd.Text = template.FileEnd;
                    txtFileElement.Text = template.FileLine;
                    string pTitle = I18nUtils.GetString("UIStrings", "EditingName", Server.HtmlEncode(template.Name));
                    Page.Title = pTitle + " &raquo; ResourceBlender.NET";
                    lblEditTemplates.Text = pTitle;
                    litNavAddAddTemplate.Text = I18nUtils.GetString("UIStrings", "EditTemplate");
                    Session["templateid"] = template.ID;
                    Session["editingtemplate"] = bool.TrueString;
                    mltMain.ActiveViewIndex = 1;
                    break;
                case "confirmdelete":
                    Session["templateid"] = e.CommandArgument.ToString();
                    mltMain.ActiveViewIndex = 2;
                    lblConfirmDelete.Text = I18nUtils.GetString("UIStrings", "DeleteTemplatePromptName", "<em>" + Server.HtmlEncode(template.Name) + "</em>");
                    Page.Title = I18nUtils.GetString("UIStrings", "DeleteTemplate" + " &raquo; ResourceBlender.NET");
                    break;
                default:
                    mltMain.ActiveViewIndex = 0;
                    break;
            }
        } catch(Exception ex) {
            lblErrorDescription.Text = ex.Message;
            mltMain.ActiveViewIndex = 3;
        }
    }

    #region Adding/Editing

    /// <summary>
    /// Shows a form to add a new template.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void lnkNewTemplate_Click(object sender, EventArgs e) {
        Page.Title = I18nUtils.GetString("UIStrings", "NewTemplate" + " &raquo; ResourceBlender.NET");
        txtTemplateName.Text = string.Empty;
        txtFileName.Text = string.Empty;
        txtFileStart.Text = string.Empty;
        txtFileEnd.Text = string.Empty;
        txtFileElement.Text = string.Empty;
        Session["templateid"] = -1;
        Session["editingtemplate"] = bool.FalseString;
        mltMain.ActiveViewIndex = 1;
    }

    /// <summary>
    /// Saves or adds the template.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void btnSave_Click(object sender, EventArgs e) {
        if(Page.IsValid) {
            try {
                bool editing = false;
                int templateId = -1;
                try {
                    templateId = int.Parse((Session["templateid"] ?? "-1").ToString());
                    bool.TryParse((Session["editingtemplate"] ?? bool.FalseString).ToString(), out editing);
                } catch {
                    throw new ResourceBlenderException(I18nUtils.GetString("Errors", "SessionExpired"));
                }
                RBTemplate template = new RBTemplate() {
                    Name = txtTemplateName.Text.Trim(),
                    FileStart = txtFileStart.Text.Trim(),
                    FileEnd = txtFileEnd.Text.Trim(),
                    FileLine = txtFileElement.Text.Trim(),
                    FileName = txtFileName.Text.Trim()
                };
                if(template.Name.Length > 255) {
                    throw new ResourceBlenderException(I18nUtils.GetString("Errors", "StringWrongLengthFmt", I18nUtils.GetString("UIStrings", "TemplateName"), "1", "255"));
                } else if(template.FileName.Length > 255) {
                    throw new ResourceBlenderException(I18nUtils.GetString("Errors", "StringWrongLengthFmt", I18nUtils.GetString("UIStrings", "Filename"), "1", "255"));
                } else if(template.FileLine.Length > 255) {
                    throw new ResourceBlenderException(I18nUtils.GetString("Errors", "StringWrongLengthFmt", I18nUtils.GetString("UIStrings", "Element"), "1", "255"));
                }
                if(editing) {
                    template.ID = templateId;
                    ResourceBlenderDAL.EditTemplate(template);
                } else {
                    ResourceBlenderDAL.AddTemplate(template);
                }
                Session["editingtemplate"] = bool.FalseString;
                mltMain.ActiveViewIndex = 0;
                BindItemsGrid();
            } catch(Exception ex) {
                lblErrorDescription.Text = ex.Message;
                mltMain.ActiveViewIndex = 3;
            }
        }
    }
    #endregion

    #region Deleting
    /// <summary>
    /// Confirms deletion of a template and removes it from the database.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void btnOk_Click(object sender, EventArgs e) {
        try {
            int templateId = -1;
            if(!int.TryParse((Session["templateid"] ?? string.Empty).ToString(), out templateId)) {
                throw new ResourceBlenderException(I18nUtils.GetString("Errors", "SessionExpired"));
            }
            ResourceBlenderDAL.DeleteTemplate(templateId);
            mltMain.ActiveViewIndex = 0;
            BindItemsGrid();
        } catch(Exception ex) {
            lblErrorDescription.Text = ex.Message;
            mltMain.ActiveViewIndex = 3;
        }
    }
    
    /// <summary>
    /// Redirects the user to the 'Manage templates' page.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void btnCancelDelete_Click(object sender, EventArgs e) {
        mltMain.ActiveViewIndex = 0;
    }
    #endregion

}
